<?php
namespace Home\Controller;
use Think\Controller;
class CommonController extends Controller{

    protected $user_id = '';
    protected $storeList;
    protected function _initialize()
    {
        if(!session('ADMIN_ID')){
            $this->redirect('Login/index');
        }
        $sessionAdminId = session('ADMIN_ID');
        if (!empty($sessionAdminId)) {
//            $user = Db::name('user')->where('id', $sessionAdminId)->find();
//
//            if (!$this->checkAccess($sessionAdminId)) {
//                $this->error("您没有访问权限！");
//            }
//            $this->assign("admin", $user);
            $this->user_id = $sessionAdminId['user_id'];
            $this->storeList = M("store")->select();

        } else {
            if (IS_POST) {
                $this->redirect("Login/index");
            } else {
                $this->redirect("Login/index");
            }
        }
    }

    //分页
    protected function getPage($count,$page,$pageSize,$where=array()){
        $Page       = new \Think\Page($count,$pageSize);// 实例化分页类 传入总记录数和每页显示的记录数
        $Page->setConfig('header','条留言');
        $Page->setConfig('first','首页');
        $Page->setConfig('prev','上一页');
        $Page->setConfig('next','下一页');
        $Page->setConfig('last','尾页');
        $Page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%<p id="pageTips">第 '.$page.' 页/共 %TOTAL_PAGE% 页 ( '.$pageSize.' 条/页 共 %TOTAL_ROW% 条信息)</p>');
        foreach($where as $key=>$val) {
            $Page->parameter[$key]   =   $val;
        }
        $show       = $Page->show();// 分页显示输出
        return $show;
    }

    //api返回
    protected function ApiReturn($code,$msg,$data=null) {
        $return_array = array(
            'code' => $code,
            'msg' => $msg
        );
        echo json_encode($return_array);
        exit;
    }

    /**
     * 检查手机号码格式
     * @param $mobile 手机号码
     */
    protected function check_mobile($mobile){
        if(preg_match('/1[0123456789]\d{9}$/',$mobile))
            return true;
        return false;
    }

    /**
     * 检查邮箱地址格式
     * @param $email 邮箱地址
     * @return bool
     */
    protected function check_email($email){
        if(filter_var($email,FILTER_VALIDATE_EMAIL))
            return true;
        return false;
    }

    //二维数组排序
    protected function arraySort($arr,$key,$type='asc')
    {
        $keyArr = array(); // 初始化存放数组将要排序的字段值
        foreach ($arr as $k => $v) {
            $keyArr[$k] = $v[$key]; // 循环获取到将要排序的字段值
        }
        if ($type == 'asc') {
            asort($keyArr); // 排序方式,将一维数组进行相应排序
        } else {
            arsort($keyArr);
        }
        $newArray = array();
        foreach ($keyArr as $k => $v) {
            $newArray[$k] = $arr[$k]; // 循环将配置的值放入响应的下标下
        }
        $newArray = array_merge($newArray); // 重置下标
        return $newArray;
    }

    protected function set_encrypt($data, $key = 'asa')
    {
        $key    =    md5($key);
        $x        =    0;
        $len    =    strlen($data);
        $l        =    strlen($key);
        for ($i = 0; $i < $len; $i++)
        {
            if ($x == $l)
            {
                $x = 0;
            }
            $char .= $key{$x};
            $x++;
        }
        for ($i = 0; $i < $len; $i++)
        {
            $str .= chr(ord($data{$i}) + (ord($char{$i})) % 256);
        }
        return base64_encode($str);
    }


    function get_decrypt($data, $key = 'asa')
    {
        $key = md5($key);
        $x = 0;
        $data = str_replace(' ','+',$data);
        $data = base64_decode($data);
        $len = strlen($data);
        $l = strlen($key);
        for ($i = 0; $i < $len; $i++)
        {
            if ($x == $l)
            {
                $x = 0;
            }
            $char .= substr($key, $x, 1);
            $x++;
        }
        for ($i = 0; $i < $len; $i++)
        {
            if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1)))
            {
                $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
            }
            else
            {
                $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
            }
        }
        return $str;
    }

    public function create_png($text, $bool = false, $outfile = false, $level = 'H', $size = 10, $margin = 6, $saveandprint=false,$logopath,$store_name=null)
    {
        require_once '../promotion/ThinkPHP/Library/Vendor/phpqrcode/phpqrcode.php';
        $qrcode = new \QRcode();
        if ( $outfile ) {
            if (!file_exists(dirname($outfile))){
                mkdir(dirname($outfile),0777,true);
            }
            $qrcode::png($text, $outfile, $level, $size, $margin, $saveandprint);
            $QR = file_get_contents($outfile);
        } else {
            ob_start();
            $qrcode::png($text, $outfile, $level, $size, $margin, $saveandprint);
            $QR = ob_get_contents();
            ob_end_clean();
        }

        //判断是否生成带logo的二维码
        if($bool)
        {
            $font = "/data/wwwroot/default/ecmall/promotion/Public/font/msyh.ttc";
            //字体大小
            $size = 15;
            //显示的文字
            $string = $store_name;
            $num1 = $this->abslength($string)/2;
            $x1 = 301-$num1;
            $logo = imagecreate(600,100);
            $black = ImageColorAllocate($logo, 255, 255, 255);
            $black1 = ImageColorAllocate($logo, 0, 0, 0);

            imagefilledrectangle($logo,0,0,600,60,$black);
            $info = imagettftext($logo, $size, 0, $x1, 28, $black1, $font, $string);

            $QR = imagecreatefromstring(file_get_contents($outfile));    //目标图象连接资源。
            $QR_width = imagesx($QR);      //二维码图片宽度
            $QR_height = imagesy($QR);     //二维码图片高度
            $logo_width = imagesx($logo);    //logo图片宽度
            $logo_height = imagesy($logo);   //logo图片高度


            $logo_qr_width = $QR_width;   //组合之后logo的宽度(占二维码的1/5)
            $scale = $logo_width / $logo_qr_width;  //logo的宽度缩放比(本身宽度/组合后的宽度)
            $logo_qr_height = $logo_height / $scale; //组合之后logo的高度
            $from_width = ($QR_width - $logo_qr_width) / 2;  //组合之后logo左上角所在坐标点
            imagecopyresampled($QR, $logo, 0, 600, 0, 0, 580, 100, 600, 100);

            //输出图片
            imagepng($QR, $outfile);
            imagedestroy($QR);
            imagedestroy($logo);
        }
        return $outfile;
    }
    function abslength($s){
        $n = 0;
        preg_match_all("/./us",$s,$matchs);
        foreach($matchs[0] as $p){
            $n += preg_match('#^['.chr(0x1).'-'.chr(0xff).']$#',$p) ? 1 : 2;
        }
        return $n;
    }

    /**
     * 获得系统年份数组
     */
    function getSystemYearArr() {
        $year_arr = array('2010' => '2010', '2011' => '2011', '2012' => '2012', '2013' => '2013', '2014' => '2014', '2015' => '2015', '2016' => '2016', '2017' => '2017', '2018' => '2018', '2019' => '2019', '2020' => '2020');
        return $year_arr;
    }

    /**
     * 获得系统月份数组
     */
    function getSystemMonthArr() {
        $month_arr = array('1' => '01', '2' => '02', '3' => '03', '4' => '04', '5' => '05', '6' => '06', '7' => '07', '8' => '08', '9' => '09', '10' => '10', '11' => '11', '12' => '12');
        return $month_arr;
    }

    /**
     * 获得系统周数组
     */
    function getSystemWeekArr() {
        $week_arr = array('1' => '周一', '2' => '周二', '3' => '周三', '4' => '周四', '5' => '周五', '6' => '周六', '7' => '周日');
        return $week_arr;
    }

    /**
     * 获取某月的最后一天
     */
    function getMonthLastDay($year, $month) {
        $t = mktime(0, 0, 0, $month + 1, 1, $year);
        $t = $t - 60 * 60 * 24;
        return $t;
    }

    /**
     * 获得系统某月的周数组，第一周不足的需要补足
     */
    function getMonthWeekArr($current_year, $current_month) {
        //该月第一天
        $firstday = strtotime($current_year . '-' . $current_month . '-01');
        //该月的第一周有几天
        $firstweekday = (7 - date('N', $firstday) + 1);
        //计算该月第一个周一的时间
        $starttime = $firstday - 3600 * 24 * (7 - $firstweekday);
        //该月的最后一天
        $lastday = strtotime($current_year . '-' . $current_month . '-01' . " +1 month -1 day");
        //该月的最后一周有几天
        $lastweekday = date('N', $lastday);
        //该月的最后一个周末的时间
        $endtime = $lastday - 3600 * 24 * $lastweekday;
        $step = 3600 * 24 * 7; //步长值
        $week_arr = array();
        for ($i = $starttime; $i < $endtime; $i = $i + 3600 * 24 * 7) {
            $week_arr[] = array('key' => date('Y-m-d', $i) . '|' . date('Y-m-d', $i + 3600 * 24 * 6), 'val' => date('Y-m-d', $i) . '~' . date('Y-m-d', $i + 3600 * 24 * 6));
        }
        return $week_arr;
    }
    /**
     * 处理搜索时间
     */
    function dealwithSearchTime($search_arr) {
        //初始化时间
        //天
        if (!$search_arr['search_time']) {
            $search_arr['search_time'] = date('Y-m-d', time());
        }
        $search_arr['day']['search_time'] = strtotime($search_arr['search_time']); //搜索的时间
        //周
        if (!$search_arr['searchweek_year']) {
            $search_arr['searchweek_year'] = date('Y', time());
        }
        if (!$search_arr['searchweek_month']) {
            $search_arr['searchweek_month'] = date('m', time());
        }
        if (!$search_arr['searchweek_week']) {
            $search_arr['searchweek_week'] = implode('|', $this->getWeek_SdateAndEdate(time()));
        }
        $weekcurrent_year = $search_arr['searchweek_year'];
        $weekcurrent_month = $search_arr['searchweek_month'];
        $weekcurrent_week = $search_arr['searchweek_week'];
        $search_arr['week']['current_year'] = $weekcurrent_year;
        $search_arr['week']['current_month'] = $weekcurrent_month;
        $search_arr['week']['current_week'] = $weekcurrent_week;

        //月
        if (!$search_arr['searchmonth_year']) {
            $search_arr['searchmonth_year'] = date('Y', time());
        }
        if (!$search_arr['searchmonth_month']) {
            $search_arr['searchmonth_month'] = date('m', time());
        }
        $monthcurrent_year = $search_arr['searchmonth_year'];
        $monthcurrent_month = $search_arr['searchmonth_month'];
        $search_arr['month']['current_year'] = $monthcurrent_year;
        $search_arr['month']['current_month'] = $monthcurrent_month;
        return $search_arr;
    }
    /**
     * 获取本周的开始时间和结束时间
     */
    function getWeek_SdateAndEdate($current_time) {
        $current_time = strtotime(date('Y-m-d', $current_time));
        $return_arr['sdate'] = date('Y-m-d', $current_time - 86400 * (date('N', $current_time) - 1));
        $return_arr['edate'] = date('Y-m-d', $current_time + 86400 * (7 - date('N', $current_time)));
        return $return_arr;
    }

    public function getCurl($url){
        $info=curl_init();
        curl_setopt($info,CURLOPT_RETURNTRANSFER,true);
        curl_setopt($info,CURLOPT_HEADER,0);
        curl_setopt($info,CURLOPT_NOBODY,0);
        curl_setopt($info,CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($info,CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($info,CURLOPT_URL,$url);
        $output= curl_exec($info);
        curl_close($info);
        return $output;
    }

    function postCurl($url,$data)
    {
        $ch = curl_init();
        $header = "Accept-Charset: utf-8";
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        if (ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off')) {
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        }
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);
        if (curl_errno($ch)) {
            return false;
        }else{
            return $tmpInfo;
        }
    }

}